﻿using Common.Communal;
using ERP.Domain.Scheduling;
using Scheduling.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scheduling.Services.Calendars
{
    public class CalendarServices : ICalendarServices
    {
        public CalendarServices(ICalendarRepository calendarRepository)
        {
            CalendarRepository = calendarRepository;
        }

        public ICalendarRepository CalendarRepository { get; }

        public async Task<ApiResult<int>> AddCalendar(Calendar calendar)
        {
            ApiResult<int> result = new ApiResult<int>();

            try
            {
                if (calendar == null)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "日历信息不能为空";
                    return result;
                }

                if (calendar.CalendarDate == default)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "日期不能为空";
                    return result;
                }

                result.Code = EnumCode.Ok;
                result.Message = "日历添加成功";
                var affected = await CalendarRepository.AddAsync(calendar);
                result.Data = affected;
            }
            catch (Exception ex)
            {
                result.Code = EnumCode.Fail;
                result.Message = $"添加日历失败：{ex.Message}";
            }

            return await Task.FromResult(result);
        }

        public async Task<ApiResult<int>> AddCalendars(List<Calendar> calendars)
        {
            ApiResult<int> result = new ApiResult<int>();

            try
            {
                if (calendars == null || calendars.Count == 0)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "日历集合不能为空";
                    return result;
                }

                // 过滤无效数据并去重（按日期）
                var valid = calendars
                    .Where(c => c != null && c.CalendarDate != default)
                    .GroupBy(c => c.CalendarDate.Date)
                    .Select(g => g.First())
                    .ToList();

                if (valid.Count == 0)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "没有有效的日历数据";
                    return result;
                }

                int affectedTotal = 0;
                foreach (var item in valid)
                {
                    affectedTotal += await CalendarRepository.AddAsync(item);
                }

                result.Code = EnumCode.Ok;
                result.Message = "日历批量添加成功";
                result.Data = affectedTotal;
            }
            catch (Exception ex)
            {
                result.Code = EnumCode.Fail;
                result.Message = $"批量添加日历失败：{ex.Message}";
            }

            return await Task.FromResult(result);
        }

        public async Task<ApiResult<int>> UpdCalendar(Calendar calendar)
        {
            ApiResult<int> result = new ApiResult<int>();

            try
            {
                if (calendar == null)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "日历信息不能为空";
                    return result;
                }

                if (calendar.CalendarId <= 0)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "日历ID无效";
                    return result;
                }

                // 获取已跟踪实体，避免重复跟踪
                var existing = await CalendarRepository.GetModelAsync(calendar.CalendarId);
                if (existing == null)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "要修改的日历不存在";
                    return result;
                }

                existing.CalendarDate = calendar.CalendarDate;
                existing.IsWorkDay = calendar.IsWorkDay;
                existing.IsUrgentWorkday = calendar.IsUrgentWorkday;
                existing.UrgentReason = calendar.UrgentReason;
                existing.HoildayType = calendar.HoildayType;

                result.Code = EnumCode.Ok;
                result.Message = "日历修改成功";
                var affected = await CalendarRepository.Update(existing);
                result.Data = affected;
            }
            catch (Exception ex)
            {
                result.Code = EnumCode.Fail;
                result.Message = $"修改日历失败：{ex.Message}";
            }

            return await Task.FromResult(result);
        }

        public async Task<ApiResult<int>> DeleteCalendar(Calendar calendar)
        {
            ApiResult<int> result = new ApiResult<int>();

            try
            {
                if (calendar == null || calendar.CalendarId <= 0)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "日历ID不能为空或无效";
                    return result;
                }

                var existing = await CalendarRepository.GetModelAsync(calendar.CalendarId);
                if (existing == null)
                {
                    result.Code = EnumCode.Fail;
                    result.Message = "要删除的日历不存在";
                    return result;
                }

                existing.IsDelete = true;

                result.Code = EnumCode.Ok;
                result.Message = "日历删除成功";
                var affected = await CalendarRepository.Update(existing);
                result.Data = affected;
            }
            catch (Exception ex)
            {
                result.Code = EnumCode.Fail;
                result.Message = $"删除日历失败：{ex.Message}";
            }

            return await Task.FromResult(result);
        }
    }
}
